package com.hxzy.common.redis;

import jodd.util.StringUtil;
import org.redisson.Redisson;
import org.redisson.api.NodeType;
import org.redisson.api.RedissonClient;
import org.redisson.client.RedisClientConfig;
import org.redisson.config.ClusterServersConfig;
import org.redisson.config.Config;
import org.redisson.config.ReadMode;
import org.redisson.config.SentinelServersConfig;
import org.redisson.connection.SentinelConnectionManager;
import org.redisson.misc.RedisURI;
import org.redisson.spring.starter.RedissonAutoConfigurationCustomizer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * redisson分布式锁的配置
 */
@Configuration
public class RedissonConfig    {


    /**
     * redis自带的对象
     */
    @Autowired
    private RedisProperties redisProperties;

    /**
     * 单机
     * @return
     */
    @Bean
    public RedissonClient redissonClient(){
        Config config = new Config();
        //哨兵
        if(this.redisProperties.getSentinel()!=null) {
            //哨兵对象
            RedisProperties.Sentinel sentinel = this.redisProperties.getSentinel();

            String[] sentinelAddress=new String[sentinel.getNodes().size()];
            AtomicInteger index=new AtomicInteger(0);
            //哨兵 List<String>  host:port
            sentinel.getNodes().stream().forEach(p-> {
                //  index++
                sentinelAddress[ index.getAndIncrement()]="redis://"+ p;
            });


            //哨兵模式
            SentinelServersConfig sentinelServersConfig = config.useSentinelServers()
                    .setMasterName(sentinel.getMaster())
                    .addSentinelAddress(sentinelAddress)
                    .setDatabase(this.redisProperties.getDatabase()).setReadMode(ReadMode.SLAVE);

            if(StringUtil.isNotBlank(sentinel.getPassword())){
                sentinelServersConfig.setPassword(sentinel.getPassword());
            }
            sentinelServersConfig.setDatabase(this.redisProperties.getDatabase());

        }else{
            config.useSingleServer().setAddress("redis://" + this.redisProperties.getHost() + ":" + this.redisProperties.getPort()).setPassword(this.redisProperties.getPassword()).setDatabase(this.redisProperties.getDatabase());
        }
        RedissonClient redisson = Redisson.create(config);
        return redisson;
    }

}
